<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">楼宇名称：</div>

      <el-input placeholder="请输入内容" class="search-main" v-model="params.name" clearable @clear="search"/>
      <el-button type="primary" @click="search">查询</el-button>

    </div>

    <!-- 添加楼宇 -->
    <div class="add-building">
      <el-button type="primary" size="medium" @click="handleAdd">添加楼宇</el-button>
    </div>

    <!-- 添加楼宇弹出框Dialog -->
    <el-dialog :title="form.id ? '编辑楼宇' : '添加楼宇'" :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="form" :rules="addFormRules">
        <el-form-item label="楼宇名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off" placeholder="请输入楼宇名称"></el-input>
        </el-form-item>
        <el-form-item label="楼宇层数" :label-width="formLabelWidth" prop="floors">
          <el-input v-model="form.floors" autocomplete="off" placeholder="请输入楼宇层数"></el-input>
        </el-form-item>
        <el-form-item label="在管面积" :label-width="formLabelWidth" prop="area">
          <el-input v-model="form.area" autocomplete="off"  placeholder="请输入在管面积">
            <template slot="append">m²</template>
          </el-input>
        </el-form-item>
        <el-form-item label="物业费" :label-width="formLabelWidth" prop="propertyFeePrice">
          <el-input v-model="form.propertyFeePrice" autocomplete="off"  placeholder="请输入物业费">
            <template slot="append">元/m²</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="buildingList"
      >
        <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
        />
        <el-table-column
          label="楼宇名称"
          width="180"
          prop="name"
        />
        <el-table-column
          label="层数"
          prop="floors"
        />
        <el-table-column
          label="在管面积(m²)"
          width="120"
          prop="area"
        />
        <el-table-column
          label="物业费(元/m²)"
          width="120"
          prop="propertyFeePrice"
        />
        <el-table-column
          label="状态"
          prop="status"
        >
        <template #default="scope">
          {{ formatStatus(scope.row.status) }}
        </template>
        </el-table-column>
        <el-table-column
          label="操作"
        >
          <template #default="scope">
            <el-button
              size="medium"
              type="text"
              @click="editBuilding(scope.row)"
            >编辑</el-button>

            <el-button
              size="medium"
              type="text"
              @click="handleDel(scope.row.id)"
            >删除</el-button>

          </template>

        </el-table-column>

      </el-table>
      <div class="page-container">
        <!-- @current-change切换页码用的 -->
          <el-pagination
            layout="total, prev, pager, next"
            :total="total"
            :page-size="params.pageSize"
            @current-change="handleCurrentChange"
          />
      </div>
    </div>

  </div>

</template>

<script>
import { getBuildingListAPI, createBuildingListAPI, delBuildingListAPI, editBuildingAPI } from '@/api/building'
export default {
  name: 'Building',
  data() {
    return {
      //
      buildingList: [],
      params: {
        page: 1,
        pageSize: 10,
        name: ''
      },
      total: 0,
      //控制添加楼宇弹出框，默认false
      dialogFormVisible: false,
      //form输入框名称
      form: {
        name: '',
        floors: '',
        area: '',
        propertyFeePrice: ''
      },
      formLabelWidth: '120px',
      addFormRules: {
        name: [
          { required: true, message: '请输入楼宇名称', trigger: 'blur' }
        ],
        floors: [
          { required: true, message: '请输入楼宇层数', trigger: 'blur' }
        ],
        area: [
          { required: true, message: '请输入楼宇面积', trigger: 'blur' }
        ],
        propertyFeePrice: [
          { required: true, message: '请输入楼宇物业费', trigger: 'blur' }
        ],
      }
    }
  },
  created() {
    this.getBuildingList()
  },
  methods: {
    async getBuildingList() {
      const res = await getBuildingListAPI(this.params)
      //console.log(res)
      this.buildingList = res.data.rows
      //存入总条数
      this.total = res.data.total
    },
    formatStatus(status) {
      const statusMap = {
        0: '租赁中',
        1:'闲置中'
      }
      return statusMap[status]
    },
    handleCurrentChange(page) {
      console.log(page)
      //更改页码参数
      this.params.page = page
      //重新获取数据渲染
      this.getBuildingList()
    },
    /* 计算序号，index是当前页，把当前页前面页码乘以每页的条数的积加上当前行行号（行号从0开始）加1
    比如当前页为3，每页条数10，行号为第3行就是把（3-1）*10+2+1=23，就是第3页第3行序号为23 */
    indexMethod(index) {
      return (this.params.page - 1) * this.params.pageSize + index + 1
    },
    //查询
    search() {
      this.params.page = 1
      this.getBuildingList()
    },
    //添加楼宇处理确定按钮，关闭弹框和整体校验,先校验再关弹框
    handleConfirm() {
      this.$refs.form.validate(async(valid) => {
        if (valid) {
          //如果有id，点击确认调用编辑接口进行编辑
          if (this.form.id) {
            await editBuildingAPI(this.form)
            this.$message.success('编辑成功')
            //添加成功后会回显之前添加的内容，将表单置空
            this.$refs.form.resetFields()
          } else {
            //如果没id，点击确认调用添加接口进行添加
            await createBuildingListAPI(this.form)
            this.$message.success('添加成功')
            //添加成功后会回显之前添加的内容，将表单置空
            this.$refs.form.resetFields()
          }
          //console.log('添加了')
          this.getBuildingList()
          this.dialogFormVisible = false
        }
      })
    },
    //删除楼宇
    handleDel(id) {
      this.$confirm('确认删除当前楼宇吗？', '温馨提示').then(async() => {
        await delBuildingListAPI(id)
        this.$message.success('删除成功')
        if (this.buildingList.length === 1 && this.params.page > 1) {
          this.params.page--
        }
        this.getBuildingList()
      }).catch(() => {})
    },
    //编辑楼宇
    async editBuilding(row) {
      this.dialogFormVisible = true
      const { id, area, floors, name, propertyFeePrice } = row
      this.form = { id, area, floors, name, propertyFeePrice }
    },
    //关闭添加楼宇弹框，清空表单和校验
    closeDialog() {
      this.dialogFormVisible = false
      this.form= {
        id: '',
        name: '',
        floors: '',
        area: '',
        propertyFeePrice: ''
      }
    },
    handleAdd() {
      this.dialogFormVisible = true
      this.form = {
        id: '',
        name: '',
        floors: '',
        area: '',
        propertyFeePrice: ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.department-container{
  padding:10px;
}
.search-container{
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237,237,237,.9);;
  padding-bottom: 20px;
  .search-label{
    width:100px;
  }
  .search-main{
    width: 220px;
    margin-right: 10px;
  }
}
.page-container{
    padding:4px 0px;
    text-align: right;
}
.add-building {
  margin-top: 20px;
  margin-bottom: 10px;
}
.el-form {
  width: 500px;
  
}

</style>
